﻿angular.module("umbraco").controller("Gary.MarkdownEditorController", function ($scope, assetsService, dialogService, contentResource) {
    if ($scope.model.value === null || $scope.model.value === "") {
        $scope.model.value = $scope.model.config.defaultValue;
    }

    if ($scope.model.config.width !== null && $scope.model.config.width !== "") {
        $scope.model.width = $scope.model.config.width + "px";
    } else {
        $scope.model.width = "100%";
    }

    $scope.model.height = $scope.model.config.height + "px";

    assetsService
        .load([
            "~/App_Plugins/MarkDownEditor/lib/Markdown.Converter.js?dt=" + new Date(),
            "~/App_Plugins/MarkDownEditor/lib/Markdown.Editor.js?dt=" + new Date(),
            "~/App_Plugins/MarkDownEditor/lib/Markdown.Sanitizer.js?dt=" + new Date()
        ])
        .then(function () {
            var converter2 = new Markdown.Converter();
            var editor2 = new Markdown.Editor(converter2, "-" + $scope.model.alias);
            editor2.run();

            editor2.hooks.set("insertImageDialog", function (callback) {
                dialogService.mediaPicker({
                    callback: function (data) {
                        $(data).each(function (i, item) {
                            if (item.isFolder) {
                                callback(null);
                            } else {
                                callback(item.image);
                            }
                        });
                    },
                    onlyImages: true
                });
                return true;
            });

            editor2.hooks.set("insertLinkDialog", function (callback) {
                dialogService.contentPicker({
                    callback: function (data) {
                        $(data).each(function (i, item) {
                            contentResource.getNiceUrl(item.id).then(function (url) {
                                callback(url);
                            });
                        });
                    },
                    multipicker: false
                });
                return true;
            });
        });

    assetsService.loadCss("~/App_Plugins/MarkDownEditor/lib/markdown.css");
});